﻿using System;
using System.Threading;
using UnityEngine;

namespace JH
{
    using System.Collections;

    public static class ConditionAwaiterExtensions
    {
        /// <summary>
        ///  异步行为转换为Task
        /// </summary>
        public static ConditionAwaiter WithToken(this AsyncOperation operation, CancellationToken token = default)
        {
            if (operation == null) return new ConditionAwaiter(() => true, token);
            return JTask.WaitUntil(() => operation.isDone, token);
        }

        /// <summary>
        /// 将 ConditionAwaiter 封装成协程可等待的 IEnumerator
        /// </summary>
        public static IEnumerator AsCoroutine(this ConditionAwaiter awaiter)
        {
            bool isCompleted = false;
            Exception exception = null;

            awaiter.OnCompleted(() =>
            {
                try
                {
                    awaiter.GetResult();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
                finally
                {
                    isCompleted = true;
                }
            });

            // 等待完成
            while (!isCompleted)
                yield return null;

            // 如果发生异常，抛出异常以供测试框架捕获
            if (exception != null)
                throw exception;
        }
    }
}